package com.chenjt.netty.six_gPRC.streamReqAndResp;

import com.chenjt.netty.six_gPRC.generateCode.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.time.LocalDateTime;
import java.util.Iterator;

/**
 * gRPC客户端
 *
 * 参考D:\programmer\studyWorkspace\netty\doc\grpc-java\examples\src\main\java\io\grpc\examples\helloworld\HelloWorldClient.java
 * @author chenjt
 * @date 2024/8/16 10:36
 */
public class GrpcClient {

    public static void main(String[] args) {
        // 只要客户端是以流式的形式向服务器端发送一个请求，这种请求一定都是异步的
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8899)
//                .usePlaintext(true)
                .usePlaintext()
                .build();
        // 异步
        StudentServiceGrpc.StudentServiceStub stub = StudentServiceGrpc.newStub(managedChannel);


        StreamObserver<StreamRequest> requestStreamObserver = stub.biTalk(new StreamObserver<StreamResponse>() {
            @Override
            public void onNext(StreamResponse streamResponse) {
                System.out.println(streamResponse.getResponseInfo());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("onCompleted");
            }
        });


        for (int i = 0; i < 10; i++) {
            requestStreamObserver.onNext(StreamRequest.newBuilder().setRequestInfo(LocalDateTime.now().toString()).build());

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        // 睡一下等待异步调用返回数据
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



    }



}
